package org.br.erp.rfq.po.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.br.erp.rfq.base.entity.Scmuserregionlink;
import org.br.erp.rfq.base.service.IScmuserregionlinkService;
import org.br.erp.rfq.po.entity.Scmpoattach;
import org.br.erp.rfq.po.service.IScmpoattachService;
import org.br.erp.rfq.xbj.entity.Scmxjd;
import org.jeecg.modules.base.mapper.BaseCommonMapper;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.br.erp.rfq.po.entity.Scmpoitem;
import org.br.erp.rfq.po.entity.Scmpo;
import org.br.erp.rfq.po.vo.ScmpoPage;
import org.br.erp.rfq.po.service.IScmpoService;
import org.br.erp.rfq.po.service.IScmpoitemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 采购订单
 * @Author: jeecg-boot
 * @Date:   2023-09-17
 * @Version: V1.0
 */
@Api(tags="采购订单")
@RestController
@RequestMapping("/rfq.po/scmpo")
@Slf4j
public class ScmpoController {
	@Autowired
	private IScmpoService scmpoService;
	@Autowired
	private IScmpoitemService scmpoitemService;

	 @Autowired
	 private IScmpoattachService scmpoattachService;

	 @Autowired
	 private BaseCommonMapper baseCommonMapper;

	 @Autowired
	 private IScmuserregionlinkService scmuserregionlinkService;
	
	/**
	 * 分页列表查询
	 *
	 * @param scmpo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "采购订单-分页列表查询")
	@ApiOperation(value="采购订单-分页列表查询", notes="采购订单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<Scmpo>> queryPageList(Scmpo scmpo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Scmpo> queryWrapper = QueryGenerator.initQueryWrapper(scmpo, req.getParameterMap());
		Page<Scmpo> page = new Page<Scmpo>(pageNo, pageSize);

		//判断当前人是否是供应商，
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		String selecttablevalue = baseCommonMapper.selecttablevalue("sys_user", "innervendorid", "id", sysUser.getId());

		List<Map> sys_user = baseCommonMapper.basequery("provinceflag,regionid", "sys_user", "id ='" + sysUser.getId() + "'");


		if(selecttablevalue!=null && !selecttablevalue.equalsIgnoreCase("")){
			queryWrapper.eq("vendorid",selecttablevalue);
		}else{
			QueryWrapper<Scmuserregionlink> scmuserregionlinkQueryWrapper=new QueryWrapper<>();
			scmuserregionlinkQueryWrapper.eq("userid",sysUser.getId());
			List<Scmuserregionlink> list = scmuserregionlinkService.list(scmuserregionlinkQueryWrapper);

			String regionid = sys_user.get(0).get("regionid").toString();
			String provinceflag = sys_user.get(0).get("provinceflag").toString();

			if(provinceflag!=null && provinceflag.equalsIgnoreCase("0")){
				//省公司的人登录查看
				boolean isall = false;
				if(list.size() == 0){
					queryWrapper.eq("1","2");
				}else{
					isall=false;
					if(sys_user.size() == 0){
						return Result.error("");
					}
				}
				for (Scmuserregionlink scmuserregionlink : list) {
					if(scmuserregionlink.getRegionid()== null || scmuserregionlink.getRegionid().equalsIgnoreCase("")){
						isall=true;
					}
				}
				if(isall){
					queryWrapper.exists("select 1 from scmxjd where scmxjd.billcode = scmpo.xjdbillcode and scmxjd.cityid like '"+regionid.substring(0,2)+"%'");
				}else{
          if (list.size() > 0) {
            String sql = " (";
            for (Scmuserregionlink scmuserregionlink : list) {
              String curRegionId = scmuserregionlink.getRegionid();
              sql += " head.cityid like '" + curRegionId.substring(0, 4) + "%' or ";
            }
            sql = sql.substring(0, sql.length() - 3) + ")";
            queryWrapper.exists(
                "select 1 from scmxjd head where  head.billcode = scmpo.xjdbillcode and " + sql);
					}else{
			  queryWrapper.eq("1","2");
		  }
				}
			}else if(provinceflag!=null && provinceflag.equalsIgnoreCase("1")){
				//地区公司的人
				queryWrapper.exists("select 1 from scmxjd head where head.billcode = scmpo.xjdbillcode and head.cityid like '"+regionid.substring(0,4)+"%'");
			}else if(provinceflag!=null && provinceflag.equalsIgnoreCase("2")){
				//只能查看本人数据
				queryWrapper.exists("select 1 from scmxjd head where head.billcode = scmpo.xjdbillcode and head.cityid = '"+regionid+"'");
			}else{
				queryWrapper.eq("1","2");
			}


		}
		IPage<Scmpo> pageList = scmpoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param scmpoPage
	 * @return
	 */
	@AutoLog(value = "采购订单-添加")
	@ApiOperation(value="采购订单-添加", notes="采购订单-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ScmpoPage scmpoPage) {
		Scmpo scmpo = new Scmpo();
		BeanUtils.copyProperties(scmpoPage, scmpo);
		scmpoService.saveMain(scmpo, scmpoPage.getScmpoitemList(),scmpoPage.getScmpoattachList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param scmpoPage
	 * @return
	 */
	@AutoLog(value = "采购订单-编辑")
	@ApiOperation(value="采购订单-编辑", notes="采购订单-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ScmpoPage scmpoPage) {
		Scmpo scmpo = new Scmpo();
		BeanUtils.copyProperties(scmpoPage, scmpo);
		Scmpo scmpoEntity = scmpoService.getById(scmpo.getId());
		if(scmpoEntity==null) {
			return Result.error("未找到对应数据");
		}
		scmpoService.updateMain(scmpo, scmpoPage.getScmpoitemList(),scmpoPage.getScmpoattachList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购订单-通过id删除")
	@ApiOperation(value="采购订单-通过id删除", notes="采购订单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		scmpoService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "采购订单-批量删除")
	@ApiOperation(value="采购订单-批量删除", notes="采购订单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.scmpoService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "采购订单-通过id查询")
	@ApiOperation(value="采购订单-通过id查询", notes="采购订单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Scmpo> queryById(@RequestParam(name="id",required=true) String id) {
		Scmpo scmpo = scmpoService.getById(id);
		if(scmpo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(scmpo);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "采购订单分录通过主表ID查询")
	@ApiOperation(value="采购订单分录主表ID查询", notes="采购订单分录-通主表ID查询")
	@GetMapping(value = "/queryScmpoitemByMainId")
	public Result<List<Scmpoitem>> queryScmpoitemListByMainId(@RequestParam(name="id",required=true) String id) {
		List<Scmpoitem> scmpoitemList = scmpoitemService.selectByMainId(id);
		return Result.OK(scmpoitemList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param scmpo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Scmpo scmpo) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<Scmpo> queryWrapper = QueryGenerator.initQueryWrapper(scmpo, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<Scmpo> scmpoList = scmpoService.list(queryWrapper);

      // Step.3 组装pageList
      List<ScmpoPage> pageList = new ArrayList<ScmpoPage>();
      for (Scmpo main : scmpoList) {
          ScmpoPage vo = new ScmpoPage();
          BeanUtils.copyProperties(main, vo);
          List<Scmpoitem> scmpoitemList = scmpoitemService.selectByMainId(main.getId());
          vo.setScmpoitemList(scmpoitemList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "采购订单列表");
      mv.addObject(NormalExcelConstants.CLASS, ScmpoPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("采购订单数据", "导出人:"+sysUser.getRealname(), "采购订单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ScmpoPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ScmpoPage.class, params);
              for (ScmpoPage page : list) {
                  Scmpo po = new Scmpo();
                  BeanUtils.copyProperties(page, po);
                  scmpoService.saveMain(po, page.getScmpoitemList(),page.getScmpoattachList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	@PostMapping(value = "generatepo")
	 public Result<String>  generatePo(@RequestBody JSONObject jsonObject){
		 ArrayList<String> ids =	(ArrayList)jsonObject.get("id");
		 scmpoService.generatePO(ids);
		 return Result.ok();
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "采购附件通过主表ID查询")
	 @ApiOperation(value="采购附件主表ID查询", notes="采购附件-通主表ID查询")
	 @GetMapping(value = "/queryScmpoattachByMainId")
	 public Result<List<Scmpoattach>> queryScmpoattachListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<Scmpoattach> scmpoattachList = scmpoattachService.selectByMainId(id);
		 return Result.OK(scmpoattachList);
	 }

	 @Transactional
	 @PostMapping(value = "updatepoflag")
	 public Result<String> updatePoFlag(@RequestBody JSONObject jsonObject){

		 String id = jsonObject.get("id").toString();
		 String flag = jsonObject.get("flag").toString();

		 Scmpo scmpo = scmpoService.getById(id);
		 scmpo.setDeliveyflag(flag);
		 scmpoService.updateById(scmpo);
		 return Result.ok("");
	 }

}
